package server.socket.handler.chat;

import server.socket.bean.EServer;
import server.socket.bean.ESocket;
import server.socket.bean.Message;
import server.socket.handler.ClientHandler;
import server.socket.server.ChatServer;
import server.util.InfoUtils.Info;
import server.util.InfoUtils.InfoUtil;
import server.util.MyUtils;

import java.io.IOException;

public class ChatClientHandler extends ClientHandler {
    private int userId = -1;

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
        ((ChatServer) server).register(userId, this);
    }

    public ChatClientHandler(EServer server, ESocket client, ChatInfoHandler chatInfoHandler) {
        super(server, client);
        this.infoHandler = chatInfoHandler;
        //为ChatInfoHandler设置ChatClientHandler
        ((ChatInfoHandler) this.infoHandler).setClientHandler(this);
    }

    @Override
    public void update() {
        System.out.println("ChatHandler  update()");
        new Thread(() -> {
            try {
                while (true) {
                    System.out.println("server receiving");
                    Info info = MyUtils.fromJson(client.readUTF(), Info.class);
                    System.out.println("收到" + info);
                    infoHandler.handleInfo(info);
                }
            } catch (IOException e) {
                e.printStackTrace();
                ((ChatServer) server).logout(userId);
                server.remove(this);
            }
        }).start();
    }

    public void sendMessage2Server(Message message) {
        ((ChatServer) server).sendMessage(message);
    }

    public void sendInfo2Client(Message message) {
        try {
            //转化为info-->转化为json-->发送
            client.writeUTF(MyUtils.toJson(InfoUtil.getInfo(message),2));
            System.out.println("发送" + MyUtils.toJson(InfoUtil.getInfo(message),2));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendInfo2Client(Info info){
        try {
            //转化为info-->转化为json-->发送
            client.writeUTF(MyUtils.toJson(info));
            System.out.println("发送" + MyUtils.toJson(info));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
